package com.manor.main.activity;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.widget.ProgressBar;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.fastjson.JSON;
import com.baidu.idl.face.platform.FaceStatusEnum;
import com.baidu.idl.face.platform.LivenessTypeEnum;
import com.baidu.idl.face.platform.ui.FaceLivenessActivity;
import com.baidu.idl.face.platform.utils.BitmapUtils;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.impl.LoadingPopupView;
import com.manor.common.CommonAppConfig;
import com.manor.common.Constants;
import com.manor.common.em.AuthType;
import com.manor.common.event.AuthResultEvent;
import com.manor.common.http.CommonHttpUtil;
import com.manor.common.http.HttpCallback;
import com.manor.common.http.JCommonHttpUtil;
import com.manor.common.http.JHttpCallback;
import com.manor.common.http.PitUtil;
import com.manor.common.utils.BitmapUtil;
import com.manor.common.utils.DateFormatUtil;
import com.manor.common.utils.DialogUitl;
import com.manor.common.utils.KLog;
import com.manor.common.utils.L;
import com.manor.common.utils.RouteUtil;
import com.manor.common.utils.StringUtil;
import com.manor.common.utils.ToastUtil;
import com.orhanobut.logger.Logger;
import com.qiniu.android.storage.UploadManager;
import com.qiniu.android.storage.UploadOptions;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;

import java.util.HashMap;

/**
 * @version 1.0
 * @date 2020/5/20  10:15
 */
@Route(path = RouteUtil.MAIN_FACE_EXP)
public class FaceExpActivity extends FaceLivenessActivity {
    public static final String IS_FROM_DEPOSIT = "isFromDeposit";//是否从提现过来
    private Dialog mLoading;
    private UploadManager uploadManager;
    private String urlKey = "";
    private String mToken;
    private boolean isDeposit;
    private AuthType mType;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getIntent().getExtras() == null)
            finish();
        mType = (AuthType) getIntent().getExtras().getSerializable(Constants.H_TYPE);

    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (intent.getExtras() == null)
            finish();
        mType = (AuthType) intent.getExtras().getSerializable(Constants.H_TYPE);
    }

    @Override
    public void finish() {
        if (mLoading != null) {
            mLoading.dismiss();
            mLoading = null;
        }
        super.finish();
    }

    @Override
    public void onLivenessCompletion(FaceStatusEnum status, String message, HashMap<String, String> base64ImageMap) {
        super.onLivenessCompletion(status, message, base64ImageMap);
        if (status == FaceStatusEnum.OK && mIsCompletion) {
            //[Eye, Mouth, HeadLeftOrRight, bestImage0]
            stopPreview();
//            String baseStr = base64ImageMap.get("bestImage0");
            String baseStr = getBaseStr(base64ImageMap);
            Bitmap bmp = BitmapUtils.base64ToBitmap(baseStr);
            String authfile = BitmapUtil.saveBitmap(FaceExpActivity.this, bmp);

            uploadPlan(authfile, baseStr);
        } else if (status == FaceStatusEnum.Error_DetectTimeout ||
                status == FaceStatusEnum.Error_LivenessTimeout ||
                status == FaceStatusEnum.Error_Timeout) {
            ToastUtil.show("检测采集超时");
        }
    }


    private String getBaseStr(HashMap<String, String> map){
        if (map.containsKey(LivenessTypeEnum.Eye.toString()))
            return map.get(LivenessTypeEnum.Eye.toString());
        if (map.containsKey(LivenessTypeEnum.Mouth.toString()))
            return map.get(LivenessTypeEnum.Mouth.toString());
        if (map.containsKey(LivenessTypeEnum.HeadUp.toString()))
            return map.get(LivenessTypeEnum.HeadUp.toString());
        if (map.containsKey(LivenessTypeEnum.HeadDown.toString()))
            return map.get(LivenessTypeEnum.HeadDown.toString());
        if (map.containsKey(LivenessTypeEnum.HeadLeft.toString()))
            return map.get(LivenessTypeEnum.HeadLeft.toString());
        if (map.containsKey(LivenessTypeEnum.HeadRight.toString()))
            return map.get(LivenessTypeEnum.HeadRight.toString());
        if (map.containsKey(LivenessTypeEnum.HeadLeftOrRight.toString()))
            return map.get(LivenessTypeEnum.HeadLeftOrRight.toString());
       return map.get("bestImage0");
    }


    /**
     * 获取七牛token
     */
    private void uploadPlan(String authDate, String baseStr) {
        CommonHttpUtil.getUploadQiNiuToken(new HttpCallback() {
            @Override
            public void onSuccess(int code, String msg, String info) {
                if (code == 0) {
                    Logger.i(info);
                    String result = PitUtil.strGetFirst(info);

                    mToken = JSON.parseObject(result).getString("token");
                    L.e("上传token", "-------上传的token------>" + mToken);
                    uploadAuth(authDate, baseStr);
                } else {
                    ToastUtil.show(msg);
                    finish();
                }
            }

            @Override
            public void onError() {
                super.onError();
                finish();
            }
        });

    }

    /**
     * 上传认证图片到七牛
     */
    private void uploadAuth(String authDate, String baseStr) {
        if (StringUtil.isNotEmpty(authDate)) {
            if (mLoading == null) {
                mLoading = DialogUitl.loadingDialog(FaceExpActivity.this, "身份认证中");
            }
            mLoading.show();
            uploadFile(authDate, new UploadListener() {
                @Override
                public void onUploadSuccess(String url) {
                    KLog.e("onUploadSuccess", url);
                    if (mLoading != null) {
                        mLoading.dismiss();
                    }
                    if (!"".equals(url)) {
                        //上传认证或者提现
                        if (mType == AuthType.TYPE_AUTH) {//认证
                            doFirstAuth(url, baseStr);
                        } else {
                            doExtractAuth(url, baseStr);
                        }
                    } else {
                        ToastUtil.show("上传失败，请稍后重试");
                        finish();
                    }
                }

                @Override
                public void onUploadFail(Error error) {
                    if (mLoading != null) {
                        mLoading.dismiss();
                    }
                    finish();
                }
            });
        }
    }


    /**
     * 首次认证
     */
    private void doFirstAuth(String url, String baseStr) {
        LoadingPopupView popup = new XPopup.Builder(FaceExpActivity.this)
                .asLoading("校验中...");
        popup.show();
        JCommonHttpUtil.getZAY(url, baseStr, new JHttpCallback() {
            @Override
            public void onSuccess(int code, String msg, String info) {
                popup.dismiss();
                if (code == 200) {
                    ToastUtil.show("认证成功");
                } else {
                    ToastUtil.show(msg);
                }
                finish();
            }

            @Override
            public void onError() {
                super.onError();
                popup.dismiss();
                finish();
            }
        });

    }

    /**
     * 提现检测
     */
    private void doExtractAuth(String imgUrl, String baseUrl) {
        LoadingPopupView popup = new XPopup.Builder(FaceExpActivity.this)
                .asLoading("校验中...");
        popup.show();
        String type = mType == AuthType.TYPE_LOGIN ? "2" : "1";
        JCommonHttpUtil.extractAuth(type, baseUrl, new JHttpCallback() {
            @Override
            public void onSuccess(int code, String msg, String info) {
                popup.dismiss();
                EventBus.getDefault().post(new AuthResultEvent(code, msg, imgUrl, mType));
                finish();
            }

            @Override
            public void onError() {
                super.onError();
                popup.dismiss();
                finish();
            }
        });
    }


    //上传单个文件
    public void uploadFile(final String filePath, final UploadListener uploadListener) {

        if (filePath == null) {
            uploadListener.onUploadFail(new Error(""));
            return;
        }
        if (uploadManager == null) {
            uploadManager = new UploadManager();
        }
        String name = "AUTH_IMG_" + CommonAppConfig.getInstance().getUid() + DateFormatUtil.getCurTimeString() + ".png";
        uploadManager.put(filePath, name, mToken,
                (key, respInfo, jsonData) -> {

                    if (respInfo.isOK()) {
                        try {
                            urlKey = jsonData.getString("key");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                        uploadListener.onUploadSuccess(urlKey);

                    } else {
                        Logger.i(respInfo.error);
                        uploadListener.onUploadFail(new Error("上传失败" + respInfo.error));
                    }
                }, new UploadOptions(null, null, false,
                        (key, percent) -> {
//                                        progressbar.setProgress((int) (percent * 100));
                            new ProgressBar(FaceExpActivity.this).isShown();
                        }, null));
    }


    //上传回调
    public interface UploadListener {
        void onUploadSuccess(String url);

        void onUploadFail(Error error);
    }


}
